
package com.skplanet.oneplusonewindow.moimserver.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.skplanet.oneplusonewindow.moimserver.dao.UserDAO;
import com.skplanet.oneplusonewindow.moimserver.domain.Moim_User;
import com.skplanet.oneplusonewindow.moimserver.util.StringUtils;


@Service( value="userService" )
@Transactional
public class UserService {

	@Autowired
	private UserDAO userDAO;

	@Autowired
	private PasswordEncoder passwordEncoder;
	
	
	@Transactional
	public void update(Moim_User user){
		userDAO.update(user);
	}
	

	
	@Transactional
	public String addUser(Moim_User user) {
		
		// 이름안의 공백은 1개만 허용 
		user.setName( user.getName().replaceAll( "\\s{2,}", " " ) ) ;
		
		// salt 생성
		String salt = StringUtils.genRandomString( 10 );
		user.setSalt( salt );
		user.setPassword( passwordEncoder.encodePassword( user.getPassword(), salt ) );		
		
		user.setAuthority("ROLE_USER");
		
		userDAO.save( user );
		return "redirect:/user/welcome";
	}

	@Transactional(readOnly = true)
	public Moim_User select( String userId ) {
		Moim_User user = userDAO.select( userId );
		return user;
	}
	
	@Transactional
	public void changePassword( String userId, String password ) {
		Moim_User user = userDAO.select( userId );
		user.setPassword(passwordEncoder.encodePassword( password, user.getSalt() ) );
	}
	
	@Transactional
	public void deleteUser( long userId ){
		userDAO.delete( new Moim_User(userId) );
	}

	@Transactional(readOnly = true)
	public long getUserIdFromName( String name ) {
		return (long) userDAO.findColumnByObject( "id", "name", name );
	}
	@Transactional(readOnly = true)
	public String getUserNameFromId( long id ) {
		return (String) userDAO.findColumnByObject( "name", "id", id );
	}
	@Transactional(readOnly = true)
	public List<Moim_User> getAllUser(){
		return userDAO.getAll();
	}

	@Transactional(readOnly = true)
	public boolean nicknameExists(String nickname) {
		return userDAO.rowExists("nickname", nickname);
	}
	@Transactional(readOnly = true)
	public boolean nameExists(String name) {
		return userDAO.rowExists("name", name);
	}

	@Transactional(readOnly = true)
	public Moim_User getUserFromName(String name) {
		return (Moim_User)userDAO.findUniqByObject("name", name);
	} 
	
	public boolean checkEqualsPassword(Moim_User user, String currentPassword) {
		String repositoryPassword = user.getPassword();
		String encodedPassword = passwordEncoder.encodePassword( currentPassword, user.getSalt() ) ;
		return repositoryPassword.equals(encodedPassword);
	}


}